package com.authorization.authorizationserveronsso.security.service;

import com.authorization.authorizationserveronsso.entity.Users;
import com.authorization.authorizationserveronsso.security.LoginUser;
import com.authorization.authorizationserveronsso.service.UsersService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    public UsersService usersService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        log.info("验证用户信息是否合理=====", username);

        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Users user = usersService.getUser(username);
        if (user == null)
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }

        // 3. 对用户信息做封装处理
//        UserDetails userDetails = new OAuthTradeUser(user);
//        return userDetails;

        return createLoginUser(user);
    }

    /**
     * 根据当前登录信息获取 对应的权限
     * @param user
     * @return
     */
    public UserDetails createLoginUser(Users user){
        return new LoginUser(user);
    }
}
